// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const chatHistory = document.getElementById('chatHistory');
    const userInput = document.getElementById('userInput');
    const sendBtn = document.getElementById('sendBtn');
    const schemaBtn = document.getElementById('schemaBtn');
    const importBtn = document.getElementById('importBtn');
    const schemaModal = document.getElementById('schemaModal');
    const importModal = document.getElementById('importModal');
    const submitSchemaBtn = document.getElementById('submitSchemaBtn');
    const submitImportBtn = document.getElementById('submitImportBtn');
    const fileInput = document.getElementById('fileInput');
    const selectedFileName = document.getElementById('selectedFileName');
    const allowJoinsOption = document.getElementById('allowJoinsOption');
    const complexAggregationsOption = document.getElementById('complexAggregationsOption');
    const applyOptionsBtn = document.getElementById('applyOptionsBtn');
    const statusIndicator = document.getElementById('statusIndicator');
    const settingsBtn = document.getElementById('settingsBtn');
    const settingsModal = document.getElementById('settingsModal');
    const aiModelSelect = document.getElementById('aiModelSelect');
    let isSettingsOpen = false;
    // 标记是否使用导入的数据
    let usingImportedData = false;

    // 切换设置弹窗
    settingsBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        isSettingsOpen = !isSettingsOpen;
        settingsModal.style.display = isSettingsOpen ? 'block' : 'none';
    });

    // 点击其他地方关闭设置弹窗
    document.addEventListener('click', (e) => {
        if (isSettingsOpen && !settingsModal.contains(e.target) && e.target !== settingsBtn) {
            isSettingsOpen = false;
            settingsModal.style.display = 'none';
        }
    });

    // 阻止设置弹窗内部点击事件冒泡
    settingsModal.addEventListener('click', (e) => {
        e.stopPropagation();
    });
    
    // 当前查询选项
    let queryOptions = {
        allow_joins: false,
        complex_aggregations: false
    };
    
    // 打开模态框 - 导入数据
    importBtn.addEventListener('click', () => {
        importModal.style.display = 'flex';
    });
    
    // 关闭模态框
    document.querySelectorAll('.close-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            // 获取当前按钮所在的模态框
            const modal = btn.closest('.modal');
            if (modal) {
                modal.style.display = 'none';
            }
        });
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        document.querySelectorAll('.modal').forEach(modal => {
            if (e.target === modal) {
                modal.style.display = 'none';
            }
        });
    });
    
    // 显示选择的文件名
    fileInput.addEventListener('change', () => {
        if (fileInput.files.length > 0) {
            selectedFileName.textContent = fileInput.files[0].name;
        } else {
            selectedFileName.textContent = '未选择文件';
        }
    });
    
    // 提交数据导入
    submitImportBtn.addEventListener('click', async () => {
        try {
            if (fileInput.files.length === 0) {
                addSystemMessage('请先选择要导入的数据文件');
                return;
            }
            
            updateStatus('导入中...');
            
            // 调用后端API
            // 注释: 此处需要调用POST /api/database/import API将文件数据提交给后端
            const response = await importDataToBackend(fileInput.files[0]);
            
            if (response.success) {
                usingImportedData = true;
                updateDataSourceIndicator();
                
                addSystemMessage(`数据导入成功！共导入 ${response.records_imported} 条记录。系统已自动识别数据结构。`);
                importModal.style.display = 'none';
                updateStatus('就绪');
            } else {
                addSystemMessage(`导入失败: ${response.message}`);
                updateStatus('错误');
            }
        } catch (error) {
            console.error('导入数据错误:', error);
            addSystemMessage('导入数据时发生错误');
            updateStatus('错误');
        }
    });
    
    // 应用查询选项
    applyOptionsBtn.addEventListener('click', async () => {
        queryOptions = {
            allow_joins: allowJoinsOption.checked,
            complex_aggregations: complexAggregationsOption.checked
        };
        
        try {
            // 调用后端API
            // 注释: 此处需要调用PUT /api/options API将选项设置提交给后端
            const response = await updateOptionsInBackend(queryOptions);
            
            if (response.success) {
                addSystemMessage('查询选项已更新');
            } else {
                addSystemMessage(`更新选项失败: ${response.message}`);
            }
        } catch (error) {
            console.error('更新查询选项错误:', error);
            addSystemMessage('更新查询选项时发生错误');
        }
    });
    
    // 发送消息
    sendBtn.addEventListener('click', sendMessage);
    
    // 按下Enter键发送消息(Shift+Enter为换行)
    userInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
    
    // 发送消息函数
    async function sendMessage() {
        const message = userInput.value.trim();
        if (!message) return;
        
        // 添加用户消息到聊天区
        addUserMessage(message);
        userInput.value = '';
        
        try {
            updateStatus('思考中...');
            
            // 调用后端API
            // 注释: 此处需要调用POST /api/chat/message API将用户消息发送给后端
            const response = await sendMessageToBackend(message, queryOptions);
            
            // 添加AI回复到聊天区
            addBotMessage(response);
            updateStatus('就绪');
        } catch (error) {
            console.error('发送消息错误:', error);
            addSystemMessage('发送消息时发生错误');
            updateStatus('错误');
        }
    }

    // 更新数据源指示器
    function updateDataSourceIndicator() {
        currentDataSource.textContent = usingImportedData ? "导入的数据" : "已配置数据库";
    }

    // 添加用户消息到聊天区
    function addUserMessage(text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message user-message';
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.innerText = text;
        
        messageDiv.appendChild(contentDiv);
        chatHistory.appendChild(messageDiv);
        scrollToBottom();
    }
    
    // 添加AI回复到聊天区
    function addBotMessage(response) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message bot-message';
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.innerText = response.response;
        
        messageDiv.appendChild(contentDiv);
        
        // 如果有SQL查询，添加SQL代码块
        if (response.sql_generated) {
            const sqlDiv = document.createElement('div');
            sqlDiv.className = 'message-sql';
            sqlDiv.innerText = response.sql_generated;
            messageDiv.appendChild(sqlDiv);
        }
        
        // 如果有查询结果，添加结果表格
        if (response.results && response.results.length > 0) {
            const resultsDiv = document.createElement('div');
            resultsDiv.className = 'message-results';
            
            const table = document.createElement('table');
            table.className = 'results-table';
            
            // 表头
            const thead = document.createElement('thead');
            const headerRow = document.createElement('tr');
            
            // 假设所有结果具有相同的结构
            const firstResult = response.results[0];
            Object.keys(firstResult).forEach(key => {
                const th = document.createElement('th');
                th.innerText = key;
                headerRow.appendChild(th);
            });
            
            thead.appendChild(headerRow);
            table.appendChild(thead);
            
            // 表体
            const tbody = document.createElement('tbody');
            response.results.forEach(result => {
                const row = document.createElement('tr');
                
                Object.values(result).forEach(value => {
                    const td = document.createElement('td');
                    td.innerText = value;
                    row.appendChild(td);
                });
                
                tbody.appendChild(row);
            });
            
            table.appendChild(tbody);
            resultsDiv.appendChild(table);
            messageDiv.appendChild(resultsDiv);
        }
        
        chatHistory.appendChild(messageDiv);
        scrollToBottom();
    }
    
    // 添加系统消息到聊天区
    function addSystemMessage(text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message system-message';
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.innerText = text;
        
        messageDiv.appendChild(contentDiv);
        chatHistory.appendChild(messageDiv);
        scrollToBottom();
    }
    
    // 更新状态指示器
    function updateStatus(status) {
        const icon = statusIndicator.querySelector('i');
        const statusText = statusIndicator.textContent.replace(/^\S+\s/, '');
        
        switch (status) {
            case '就绪':
                icon.style.color = '#4caf50'; // 绿色
                break;
            case '处理中...':
            case '导入中...':
            case '思考中...':
                icon.style.color = '#ff9800'; // 橙色
                break;
            case '错误':
                icon.style.color = '#f44336'; // 红色
                break;
            default:
                icon.style.color = '#4caf50'; // 默认绿色
        }
        
        statusIndicator.innerHTML = `<i class="fas fa-circle"></i> ${status}`;
    }
    
    // 滚动到聊天区底部
    function scrollToBottom() {
        chatHistory.scrollTop = chatHistory.scrollHeight;
    }
    
    // 模拟后端API调用函数
    // 注释：以下函数需要替换为实际的API调用
    
    // 提交数据导入到后端
    async function importDataToBackend(file) {
        try {
            const formData = new FormData();
            formData.append('file', file);
            
            const response = await fetch('/api/database/import', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`API错误: ${response.status} ${errorText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('导入数据错误:', error);
            throw error;
        }
    }
    
    // 更新查询选项到后端
    async function updateOptionsInBackend(options) {
        try {
            // 修正数据格式: 从 options 变为 {options: options}
            const response = await fetch('/api/options', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ options: options })
            });
            
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`API错误: ${response.status} ${errorText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('更新查询选项错误:', error);
            throw error;
        }
    }
    
    // 发送消息到后端
    async function sendMessageToBackend(message, options) {
        try {
            const response = await fetch('/api/chat/message', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message, options })
            });
            
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`API错误: ${response.status} ${errorText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('发送消息错误:', error);
            throw error;
        }
    }

    // 在前端JS中添加或修改初始化信息
    function initializeChatSystem() {
        addSystemMessage("欢迎使用AI数据库问答式工具。您可以询问数据库相关问题，也可以与我进行一般对话。如需使用自定义数据，请点击'导入数据'按钮。");
    }

    // 初始化数据源指示器
    updateDataSourceIndicator();
    // initializeChatSystem();

    // 初始化时获取当前AI模型设置
    async function getCurrentAIModel() {
        try {
            const response = await fetch('/api/ai-model');
            const data = await response.json();
            aiModelSelect.value = data.current_model;
        } catch (error) {
            console.error('获取AI模型设置失败:', error);
        }
    }
    
    // 更新AI模型设置
    async function updateAIModel(model) {
        try {
            const response = await fetch('/api/ai-model', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ model: model })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            if (data.success) {
                addSystemMessage(`已切换至${data.model_name}`);
            }
        } catch (error) {
            console.error('更新AI模型失败:', error);
            addSystemMessage('更新AI模型设置失败');
        }
    }
    
    // 应用设置按钮点击事件
    applyOptionsBtn.addEventListener('click', async () => {
        // 更新查询选项
        queryOptions = {
            allow_joins: allowJoinsOption.checked,
            complex_aggregations: complexAggregationsOption.checked
        };
        
        // 更新AI模型
        await updateAIModel(aiModelSelect.value);
        
        // 更新查询选项到后端
        await updateOptionsInBackend(queryOptions);
        
        // 关闭设置弹窗
        settingsModal.style.display = 'none';
    });
    
    // 初始化时获取当前AI模型设置
    getCurrentAIModel();
});
